package osResourceMonitor

import (
	"fmt"
	"github.com/shirou/gopsutil/cpu"
	"github.com/shirou/gopsutil/load"
	"time"
)

type LoadEr interface {
	Load(s any) (any, error)
}
type CpuInfoEr interface {
	Info(s any) (any, error)
	Count(s any) (any, error)
}
type CpuPercentEr interface {
	Total(s any) (any, error)
	Misc(s any) (any, error)
	Times(s any) (any, error)
}
type CpuEr interface {
	LoadEr
	CpuInfoEr
	CpuPercentEr
}
type LinuxCpu struct {
}

func NewCpuObject() CpuEr {
	var c CpuEr
	c = &LinuxCpu{}
	return c
}
func (l LinuxCpu) Count(s any) (any, error) {
	var sum int
	if c, err := cpu.Counts(s.(bool)); err != nil {
		return nil, err
	} else {
		sum = c
	}
	return sum, nil
}

func (l LinuxCpu) Info(s any) (any, error) {
	var cpuInfoStat []cpu.InfoStat
	var err error
	if cpuInfoStat, err = cpu.Info(); err != nil {
		return nil, err
	}
	fmt.Println("CPU info:", cpuInfoStat)
	return cpuInfoStat, nil
}
func (l LinuxCpu) Times(s any) (any, error) {
	var timeStat []cpu.TimesStat
	var err error
	if timeStat, err = cpu.Times(false); err != nil {
		return nil, err
	}
	time.Sleep(1)
	timeafter, _ := cpu.Times(false)

	//计算CPU总利用率
	var totalUtilization float64
	for i := range timeStat {
		totalUtilization += timeafter[i].Total() - timeStat[i].Total()
	}
	totalUtilization *= 100
	fmt.Printf("CPU总利用率: %.2f%%\n", totalUtilization)
	return totalUtilization, nil
}

func (l LinuxCpu) Total(s any) (any, error) {
	var percent []float64
	var err error
	if percent, err = cpu.Percent(0, true); err != nil {
		return nil, err
	}
	fmt.Println("CPU使用率: %.2f%%\n", percent)
	return percent, nil
}

func (l LinuxCpu) Load(s any) (any, error) {
	var (
		loadAvg *load.AvgStat
		err     error
	)
	if loadAvg, err = load.Avg(); err != nil {
		return nil, err
	}
	switch s.(int) {
	case 1:
		return loadAvg.Load1, nil
	case 5:
		return loadAvg.Load5, nil
	case 15:
		return loadAvg.Load15, nil
	default:
		return loadAvg.String(), nil
	}
}

func (l LinuxCpu) Misc(s any) (any, error) {
	var loadMisc *load.MiscStat
	var err error
	if loadMisc, err = load.Misc(); err != nil {
		return nil, err
	}
	fmt.Println("CPU Load misc:", *loadMisc)
	return loadMisc, nil
}
